package com.guxingke.nioserver.core;

import com.guxingke.nioserver.exception.ServerException;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class Server implements Runnable {
    private static List<SelectionKey> wpool = new LinkedList<SelectionKey>();

    private static Selector selector;
    private ServerSocketChannel sschannel;
    private InetSocketAddress address;
    protected Notifier notifier;
    private int port;

    private static int MAX_THREADS = 4;

    public Server(int port) throws Exception {
        this.port = port;

        for (int i = 0; i < MAX_THREADS; i++) {
            Thread r = new Reader();
            Thread w = new Writer();
            r.start();
            w.start();
        }

        selector = Selector.open();
        sschannel = ServerSocketChannel.open();
        address = new InetSocketAddress(port);
        ServerSocket ss = sschannel.socket();
        ss.bind(address);
        sschannel.configureBlocking(false);
        sschannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void setNotifier(Notifier notifier) {
        this.notifier = notifier;
    }

    public void run() {
        if (null == notifier) {
            throw new RuntimeException("notifier is null");
        }
        System.out.println("Server started ...");
        System.out.println("Server listening on port: " + port);
        while (true) {
            try {
                int num = 0;
                num = selector.select();
                if (num > 0) {
                    Set<SelectionKey> selectedKeys = selector.selectedKeys();

                    for (SelectionKey key : selectedKeys) {
                        selectedKeys.remove(key);
                        if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                            ServerSocketChannel ssc = (ServerSocketChannel) key
                                    .channel();
                            notifier.fireOnAccept();

                            SocketChannel sc = ssc.accept();
                            sc.configureBlocking(false);

                            HttpRequest request = new HttpRequest();
                            request.setSocketChannel(sc);
                            notifier.fireOnAccepted(request);

                            sc.register(selector, SelectionKey.OP_READ, request);
                        } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                            Reader.processRequest(key);
                            key.cancel();
                        } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                            Writer.processRequest(key);
                            key.cancel();
                        }
                    }
                } else {
                    addRegister();
                }
            } catch (Exception e) {
                notifier.fireOnError(new ServerException(600));
                continue;
            }
        }
    }

    private void addRegister() {
        synchronized (wpool) {
            while (!wpool.isEmpty()) {
                SelectionKey key = (SelectionKey) wpool.remove(0);
                SocketChannel schannel = (SocketChannel) key.channel();
                try {
                    schannel.register(selector, SelectionKey.OP_WRITE,
                            key.attachment());
                } catch (Exception e) {
                    try {
                        schannel.finishConnect();
                        schannel.close();
                        schannel.socket().close();
                        notifier.fireOnClosed((HttpRequest) key.attachment());
                    } catch (Exception e1) {
                    }
                    notifier.fireOnError(new ServerException(600));
                }
            }
        }
    }

    public static void processWriteRequest(SelectionKey key) {
        synchronized (wpool) {
            wpool.add(key);
            wpool.notifyAll();
        }
        selector.wakeup();
    }

}
